#include "bsp_ft6336.h"
#include "string.h"

#define TAG "ft6336"

void bsp_ft6336_init()
{
    uint8_t id;
    // Valid touching detect threshold
    ft6336_register_write_byte(FT5x06_ID_G_THGROUP, 70);
    ft6336_register_read(0x80, &id, 1);
    ESP_LOGI(TAG, "0x80:  %d ,defalult:70", id);
    // valid touching peak detect threshold
    ft6336_register_write_byte(FT5x06_ID_G_THPEAK, 60);
    ft6336_register_read(0x81, &id, 1);
    ESP_LOGI(TAG, "0x81:  %d ,defalult:60", id);
    // Touch focus threshold
    ft6336_register_write_byte(FT5x06_ID_G_THCAL, 16);
    // threshold when there is surface water
    ft6336_register_write_byte(FT5x06_ID_G_THWATER, 60);
    // threshold of temperature compensation
    ft6336_register_write_byte(FT5x06_ID_G_THTEMP, 10);
    // Touch difference threshold
    ft6336_register_write_byte(FT5x06_ID_G_THDIFF, 20);
    // Delay to enter 'Monitor' status (s)
    ft6336_register_write_byte(FT5x06_ID_G_TIME_ENTER_MONITOR, 2);
    // Period of 'Active' status (ms)
    ft6336_register_write_byte(FT5x06_ID_G_PERIODACTIVE, 12);
    // Timer to enter 'idle' when in 'Monitor' (ms)
    ft6336_register_write_byte(FT5x06_ID_G_PERIODMONITOR, 40);

    ft6336_register_read(0xa3, &id, 1);
    ESP_LOGI(TAG, "0xa3: 0x%x ,defalult:0x64", id);

    ft6336_register_read(0xa8, &id, 1);
    ESP_LOGI(TAG, "0xa8: 0x%x , default:0x11", id);

    ft6336_register_read(0x9f, &id, 1);
    ESP_LOGI(TAG, "0x9f  ID_G_CIPHER_MID: 0x%02x  ,default:0x26", id);

    ft6336_register_read(0xa0, &id, 1);
    ESP_LOGI(TAG, "0xa0  ID_G_CIPHER_LOW: 0x%02x ,0x02: Ft6336U 0x01: Ft6336G  ", id);
}

bool bsp_ft5x06_get_point(uint16_t *x, uint16_t *y)
{
    bool press = false;
    uint16_t touchpad_x[5] = {0};
    uint16_t touchpad_y[5] = {0};
    uint8_t touchpad_cnt = 0;
    ft6336_register_read(0x02, &touchpad_cnt, 1);
    touchpad_cnt &= 0x0f;
    uint8_t data[30];
    memset(&data, 0, 30);
    if (touchpad_cnt > 0 && touchpad_cnt < 6)
    {
        ft6336_register_read(FT5x06_TOUCH1_XH, &data, 6 * touchpad_cnt);

        for (int i = 0; i < touchpad_cnt; i += 6)
        {
            touchpad_x[i] = (uint16_t)(((uint16_t)(data[i] & 0x0f) << 8) | data[i + 1]);
            touchpad_y[i] = (uint16_t)(((uint16_t)(data[i + 2] & 0x0f) << 8) | data[i + 3]);
        }
        *x = touchpad_x[0];
        *y = touchpad_y[0];
        ESP_LOGI(TAG, "touch %d X: %d ,Y: %d", touchpad_cnt, *x, *y);
        press = true;
    }
    return press;
}